<template>
  <teleport to="body">
    <n-modal 
      v-model:show="visible" 
      preset="dialog" 
      title="添加人设" 
      :mask-closable="false"
      style="width: 500px; max-width: 90vw;"
    >
      <div class="add-character-form">
        <n-form :model="form" :rules="rules" ref="formRef" label-placement="left" label-width="80px">
          <n-form-item label="人设名称" path="characterName">
            <n-input 
              v-model:value="form.characterName" 
              placeholder="请输入人设名称"
              @keydown.enter.prevent="handleConfirm"
            />
          </n-form-item>
          
          <n-form-item label="派系" path="faction">
            <n-input 
              v-model:value="form.faction" 
              placeholder="请输入派系（可选）"
              @keydown.enter.prevent="handleConfirm"
            />
          </n-form-item>
          
          <n-form-item label="外部特征" path="externalTraits">
            <n-input 
              v-model:value="form.externalTraits" 
              type="textarea"
              placeholder="请输入外部特征（可选）"
              :autosize="{ minRows: 3, maxRows: 5 }"
            />
          </n-form-item>
        </n-form>
      </div>
      
      <template #action>
        <n-space justify="end">
          <n-button @click="handleCancel">取消</n-button>
          <n-button type="primary" @click="handleConfirm" :loading="loading">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </teleport>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import { useMessage } from 'naive-ui'

// 添加组件名称声明
defineOptions({
  name: 'AddCharacterDialog'
})

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'confirm'])

const message = useMessage()
const formRef = ref<any>(null)

// 表单数据
const form = reactive({
  characterName: '',
  faction: '',
  externalTraits: ''
})

// 表单验证规则
const rules = {
  characterName: [
    { required: true, message: '请输入人设名称', trigger: 'blur' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit('update:visible', value)
})

// 重置表单
const resetForm = () => {
  form.characterName = ''
  form.faction = ''
  form.externalTraits = ''
  if (formRef.value) {
    formRef.value.restoreValidation()
  }
}

// 监听对话框显示/隐藏
watch(() => props.visible, (newVal: boolean) => {
  if (newVal) {
    resetForm()
  }
})

// 事件处理
const handleConfirm = async () => {
  try {
    await formRef.value?.validate()
    emit('confirm', { ...form })
  } catch (error) {
    // 验证失败
  }
}

const handleCancel = () => {
  visible.value = false
}
</script>

<style scoped>
.add-character-form {
  padding: 16px 0;
}
</style>